<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Centos7 mosquitto test</title>
<script src="/vendor/jquery/jquery-1.10.2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
<!-- script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script-->
<script type="text/javascript">
	var hostname = "127.0.0.1"; //主机IP  106.14.181.32
	var hostPort = 15675; //port
	var sub_count = 0;
	var client;
	
	/* var options = {
		    timeout: 3,
		    keepAliveInterval: 30,
		    onSuccess: function () {
		        debug("CONNECTION SUCCESS");
		        client.subscribe('/topic/test', {qos: 1});
		    },
		    onFailure: function (message) {
		        debug("CONNECTION FAILURE - " + message.errorMessage);
		    }
		};
		if (location.protocol == "https:") {
		    options.useSSL = true;
		}
		debug("CONNECT TO " + wsbroker + ":" + wsport);
		client.connect(options); */
		
	function MQTTconnect() {
		client = new Paho.MQTT.Client(hostname, hostPort,'/ws', "12345678");
		client.onMessageArrived = onMessageArrived;
		client.connect({
			timeout: 3,
			keepAliveInterval: 30,
			onSuccess : onConnect
			
		});
		console.log("Host=" + hostname + ", port=" + hostPort);
	};
	// called when the client connects
	function onConnect() {
		console.log("onConnect succeeds");
		//  client.subscribe('topic');
		client.subscribe('#'); //订阅所有主题
	}
	// called when a message arrives
	function onMessageArrived(message) {
		var topic = message.destinationName;
		var payload = message.payloadString;
		console.log("onMessageArrived:" + payload);
		sub_count++;
		$('#sub_count').val('收到订阅' + sub_count + '条');
		$('#sub_message').prepend('<li>' + topic + ' = ' + payload + '</li>');
	}
	function button_onclick() {
		var topic = $('#topicsend').val();
		var text = $('#textsend').val();
		if (topic == '' || text == '') {
			alert("noTopic or noText");
			return;
		}
		var message = new Paho.MQTT.Message(text);
		message.destinationName = topic;
		message.qos = 0;
		client.send(message);
	};
	$(document).ready(function() {
		MQTTconnect();
	});
</script>
</head>

<body>
	<h1>mosquitto pub</h1>
	topic:
	<input type='text' id='topicsend' size="60" />
	<br> text :
	<input type='text' id='textsend' size="60" />
	<input type='button' value="send" id='btn' onclick="button_onclick()" />
	</br>
	<h1>mosquitto sub</h1>
	<input type='text' id='sub_count' disabled />
	<ul id='sub_message'></ul>
</body>
</html>